package com.windowes.weichang.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.windowes.weichang.access.UserContext;
import com.windowes.weichang.common.ServerResponse;
import com.windowes.weichang.dao.*;
import com.windowes.weichang.dto.DeptDTO;
import com.windowes.weichang.pojo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/***
 *
 * @author: yangqing
 * @email: qing.yang@bangdao-tech.com
 * @createTime: 2018/7/28 下午3:04
 * @description:
 *
 * sys_dept
 * sys_dept_relation
 * sys_role
 * sys_role_dept
 * sys_user_role
 *
 **/
@Service
public class AgentService {

    @Autowired
    SysDeptMapper sysDeptMapper;
    @Autowired
    SysDeptRelationMapper sysDeptRelationMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysRoleDeptMapper sysRoleDeptMapper;
    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    WUserMapper userMapper;

    @Autowired
    WDistrictMapper districtMapper;


    /**
     * 默认部门ID
     */
    public static final int CONST_DEPT_ID = 2;

    /**
     * sys_dept ,sys_dept_relation
     *
     * @param deptDTO
     * @return
     */
    @Transactional
    public ServerResponse addOrUpdate(DeptDTO deptDTO) {
        if (deptDTO.getId() == null) {

            if (deptDTO.getProvinceId() == null) {
                return ServerResponse.createByErrorMessage("请选择城市!");
            }

            //检查provineId是否被占用

            SysDept dept = sysDeptMapper.selectByProvinceId(deptDTO.getProvinceId());
            if (dept != null) {
                return ServerResponse.createByErrorMessage("该地区已被占用,请换个城市试试!");
            }


            WDistrict district = districtMapper.selectByPrimaryKey(deptDTO.getProvinceId());
            deptDTO.setName(district.getName() + "站");

            WUser wUser = null;
            if (StringUtils.isNotBlank(deptDTO.getPhone())) {
                wUser = userMapper.selectByPhone(deptDTO.getPhone());
                if (wUser != null) {
                    return ServerResponse.createByErrorMessage("用户已存在,请更换手机号!");
                }
            }

            //添加部门
            sysDeptMapper.insertSelective(deptDTO);
            //添加部门关联关系
            SysDeptRelationKey record = new SysDeptRelationKey();
            record.setAncestor(CONST_DEPT_ID);
            record.setDescendant(deptDTO.getId());
            sysDeptRelationMapper.insertSelective(record);

            // 插入用户
            addAgentRelation(deptDTO);
            //插入角色
            relateDepartAndRole(deptDTO);
        } else {
            //检查用户是否存在
            WUser wUser = null;
            if (StringUtils.isNotBlank(deptDTO.getPhone())) {
                wUser = userMapper.selectByPhone(deptDTO.getPhone());
                //检查用户是否已绑定
                if (wUser != null) {
                    SysUserRoleKey sysUserRoleKey = sysUserRoleMapper.selectByUserId(wUser.getId());
                    if (sysUserRoleKey != null) {
                        SysRoleDept roleDept = sysRoleDeptMapper.selectByRoleId(sysUserRoleKey.getRoleId());
                        if (roleDept != null && roleDept.getDeptId().compareTo(deptDTO.getId()) != 0) {
                            return ServerResponse.createByErrorMessage("用户已经绑定其他部门,请更换手机号!");
                        }
                    }

                }
            }
            //更新部门信息
            deptDTO.setProvinceId(null);
            sysDeptMapper.updateByPrimaryKeySelective(deptDTO);
            if (wUser != null) {
                SysUserRoleKey userRoleKey = sysUserRoleMapper.selectByUserId(wUser.getId());
                //用户角色关系
                sysUserRoleMapper.deleteByPrimaryKey(userRoleKey);
                //删除角色部门关系
                SysRoleDept roleDept = sysRoleDeptMapper.selectByRoleId(userRoleKey.getRoleId());
                if (roleDept != null) {
                    sysRoleDeptMapper.deleteByPrimaryKey(roleDept.getId());
                    //删除角色
                    sysRoleMapper.deleteByPrimaryKey(roleDept.getRoleId());
                }


                //新增关联关系
                //添加角色
                SysRole role = new SysRole();
                role.setRoleName("管理员");
                role.setRoleCode("ADM");
                role.setRoleDesc(deptDTO.getName() + "管理员");
                sysRoleMapper.insertSelective(role);
                //添加角色部门关系
                roleDept = new SysRoleDept();
                roleDept.setDeptId(deptDTO.getId());
                roleDept.setRoleId(role.getRoleId());
                sysRoleDeptMapper.insertSelective(roleDept);
                //添加用户角色关系
                SysUserRoleKey userRole = new SysUserRoleKey();
                userRole.setRoleId(role.getRoleId());
                userRole.setUserId(wUser.getId());
                sysUserRoleMapper.insertSelective(userRole);
            } else {
                addAgentRelation(deptDTO);
            }

        }
        return ServerResponse.createBySuccessMessage("操作成功!");
    }


    /**
     * 关联角色
     *
     * @param deptDTO
     */
    public void relateDepartAndRole(DeptDTO deptDTO) {
        //添加固定的角色
        String[] roleArr = new String[]{"客服", "财务"};
        String[] roleCodeArr = new String[]{"CUSTOM_SERVICE", "FINANCE"};


        //添加角色
        for (int i = 0; i < roleArr.length; i++) {
            String roleName = roleArr[i];
            String roleCodeItem = roleCodeArr[i];
            SysRole role = new SysRole();
            role.setRoleName(roleName);
            role.setRoleCode(roleCodeItem);
            role.setRoleDesc(deptDTO.getName());
            sysRoleMapper.insertSelective(role);
            //添加角色部门关系
            SysRoleDept roleDept = new SysRoleDept();
            roleDept.setDeptId(deptDTO.getId());
            roleDept.setRoleId(role.getRoleId());
            sysRoleDeptMapper.insertSelective(roleDept);
        }

    }

    /**
     * 添加关联关系
     *
     * @param deptDTO
     */
    private void addAgentRelation(DeptDTO deptDTO) {
        if (StringUtils.isNotBlank(deptDTO.getPhone())) {
            WUser wUser = new WUser();
            wUser.setDeptId(deptDTO.getId());
            wUser.setPassword("123456");
            wUser.setName(deptDTO.getAgentName());
            wUser.setPhone(deptDTO.getPhone());
            userMapper.insertSelective(wUser);

            //添加角色
            SysRole role = new SysRole();
            role.setRoleName("管理员");
            role.setRoleCode("ADM");
            role.setRoleDesc(deptDTO.getName() + "管理员");
            sysRoleMapper.insertSelective(role);
            //添加角色部门关系
            SysRoleDept roleDept = new SysRoleDept();
            roleDept.setDeptId(deptDTO.getId());
            roleDept.setRoleId(role.getRoleId());
            sysRoleDeptMapper.insertSelective(roleDept);
            //添加用户角色关系
            SysUserRoleKey userRole = new SysUserRoleKey();
            userRole.setRoleId(role.getRoleId());
            userRole.setUserId(wUser.getId());
            sysUserRoleMapper.insertSelective(userRole);
        }
    }


    /**
     * 查询所有代理商
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    public ServerResponse list(int pageNo, int pageSize) {
        Page<DeptDTO> page = new Page<>(pageNo, pageSize);
        Integer deptId = UserContext.getDeptId();
        List<DeptDTO> records = sysDeptMapper.selectByPage(deptId, page);
        if (!records.isEmpty()) {
            List<DeptDTO> subList = records.subList(1, records.size());
            for (DeptDTO dto : subList) {
                WUser agent = userMapper.selectADM(dto.getId());
                if (agent == null) continue;
                dto.setUserId(agent.getId());
                dto.setPhone(agent.getPhone());
                dto.setAgentName(agent.getName());
            }
            page.setRecords(subList);
        }

        return ServerResponse.createBySuccess(page);
    }


    public ServerResponse district() {
        List<SysDept> depts = sysDeptMapper.selectList();
        List<Integer> cityIds = new ArrayList<>();
        for (SysDept item : depts) {
            if (item.getProvinceId() != null) {
                cityIds.add(item.getProvinceId());
            }

        }
        return ServerResponse.createBySuccess(districtMapper.selectNotIn(cityIds));
    }

    public ServerResponse user(Integer id) {
        if (id == null) {
            return ServerResponse.createByErrorMessage("请提交id");
        }

        SysDept dept = sysDeptMapper.selectByPrimaryKey(id);
        if (dept == null) {
            return ServerResponse.createByErrorMessage("代理商不存在!");
        }
        DeptDTO dto = new DeptDTO();
        BeanUtils.copyProperties(dept, dto);

        WUser agent = userMapper.selectADM(dto.getId());
        if (agent != null) {
            dto.setUserId(agent.getId());
            dto.setPhone(agent.getPhone());
            dto.setAgentName(agent.getName());
        }
        return ServerResponse.createBySuccess(dto);
    }
}
